#ifndef __MAINREACTOR_H__
#define __MAINREACTOR_H__

#include "Acceptor.h"
#include "TimerQueue.h"
#include "LoadBalanceStrategy.h"
#include <functional>
#include <memory>
#include <vector>
#include <chrono>
#include <sys/epoll.h>
#include <arpa/inet.h>
#include <cstring>

class SubReactor;
class TcpConnection;

class MainReactor
{
    using TcpConnectionPtr = std::shared_ptr<TcpConnection>;
    using TcpConnectionCallback = std::function<void(const TcpConnectionPtr &)>;
    
public:
    MainReactor(const std::string &ip, unsigned short port, int subReactorNum = 4);
    ~MainReactor();
    
    void start();
    void stop();
    
    void setAllCallback(TcpConnectionCallback &&cb1, 
                        TcpConnectionCallback &&cb2,
                        TcpConnectionCallback &&cb3);
    
    // 定时器接口
    int64_t runAfter(std::chrono::milliseconds delay, TimerCallback &&callback);
    int64_t runEvery(std::chrono::milliseconds interval, TimerCallback &&callback);
    void cancelTimer(int64_t timerId);
    
    // 负载均衡策略接口
    void setLoadBalanceStrategy(LoadBalanceStrategy strategy);
    LoadBalanceStrategy getLoadBalanceStrategy() const { return _strategy; }
    std::pair<size_t, size_t> getConnectionRange();
    
    // 连接数管理
    void setMaxConnections(size_t maxConns) { _maxConnections = maxConns; }
    size_t getMaxConnections() const { return _maxConnections; }
    size_t getTotalConnections() const;
    
private:
    void loop();
    int createEpollFd();
    void addEpollReadFd(int fd);
    void waitEpollFd();
    void handleNewConnection();
    void handleTimerEvents();
    SubReactor* getNextSubReactor();
    SubReactor* getMinConnectionReactor(); // 取最少连接数
    SubReactor* getNextSubReactorMinConns(); //缓存优化
    SubReactor* getNextSubReactorByStrategy(const std::string& clientIP = "");
    std::string getClientIP(int connfd);
    
private:
    Acceptor _acceptor;
    int _epfd;
    std::vector<struct epoll_event> _evtList;
    bool _isLooping;
    
    std::vector<std::unique_ptr<SubReactor>> _subReactors;
    int _nextSubReactor;
    
    TimerQueue _timerQueue;
    
    TcpConnectionCallback _onNewConnection;
    TcpConnectionCallback _onMessage;
    TcpConnectionCallback _onClose;

    //缓存策略优化
    mutable std::atomic<SubReactor*> _cacheMinReactor{nullptr};
    mutable std::atomic<int64_t> _lastUpdateTime{0};
    static constexpr int64_t CACHE_VALID_MS = 100; // 100ms缓存
    
    // 负载均衡策略
    LoadBalanceStrategy _strategy = LoadBalanceStrategy::ROUND_ROBIN;
    ConsistentHash _consistentHash;
    
    // 连接数限制
    size_t _maxConnections = 10000; // 默认最大10000连接
};

#endif